﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication.CkEditor
{
	public class Uploader : IHttpHandler, System.Web.SessionState.IRequiresSessionState
	{

		public void ProcessRequest(HttpContext context)
		{
			HttpPostedFile file = context.Request.Files[0];

			string callback = context.Request.QueryString["CKEditorFuncNum"],
				path = "",
				message = "";

			if (context.Session["User"] == null)
			{
				message = "please login again.";
			} else
			{
				if (file.ContentType.StartsWith("image/"))
				{
					try
					{
						file.SaveAs(context.Server.MapPath(path = "/upload/" + DateTime.Now.ToString("yyyyMMdd-HHmmss-") + file.FileName.Split('/', '\\').Last()));
					} catch (Exception ex)
					{
						message = ex.Message;
					}
				} else
				{
					message = "please select a image file to uploader.";
				}
			}

			context.Response.ContentType = "text/html";
			context.Response.Write("<script type='text/javascript'>");
			context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + ("".Equals(message) ? path : "") + "','" + message + "')");
			context.Response.Write("</script>");
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}